package com.sdleyou.treepro.common.crontab;

import com.sdleyou.treepro.common.model.dao.UserTreeDO;
import com.sdleyou.treepro.common.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Random;
import java.util.TimeZone;

/**
 * 定时任务类
 */
@Configuration
@EnableScheduling
public class ScheduleTask {
    //每棵树上的虫子上限
    private Integer WORM_LIMIT = 3;

    @Autowired
    private MongoTemplate mongoTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 每30分钟系统给1/3玩家生成虫子
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    private void wormTask() {
        Query query = new Query(Criteria.where("worm_num").lt(this.WORM_LIMIT).and("worm_time").lt(this.todayZeroUnix()));
        //符合条件的
        long total = mongoTemplate.count(query, UserTreeDO.class);
        total = total >= 3 ? total / 3 : total;
        query.limit((int) total);
        int worms = this.randomWorms();
        Update update = new Update();
        update.set("worm_num", worms);
        update.set("worm_time", this.todayZeroUnix());
        update.set("first_worm_time", DateUtil.getDateline());
        mongoTemplate.updateMulti(query, update, UserTreeDO.class);
        logger.info("wormTask 本次执行时间: {} 修改数据: {}条 产生虫子: {}",
                DateUtil.toString(DateUtil.getDateline(), "yyyy-MM-dd HH:mm:ss"),
                total,
                worms
        );
        return;
    }

    /**
     * 获取今日0点的unix时间戳
     *
     * @return
     */
    private long todayZeroUnix() {
        Long time = System.currentTimeMillis();  //当前时间的时间戳
        return time / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
    }

    /**
     * 产生 1～3条虫子
     *
     * @return
     */
    private int randomWorms() {
        return new Random().nextInt(this.WORM_LIMIT - 1) + 1;
    }
}
